package com.imooc.maokeyang.alllearning.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
public class RedisConfig {



//    /**
//     * @description 创建redis连接工厂
//     */
//    @SuppressWarnings("deprecation")
//    private JedisConnectionFactory jedisConnectionFactory() {
//        JedisConnectionFactory factory = new JedisConnectionFactory(new JedisShardInfo(redisHost, redisPort));
//        factory.setPassword(password);
//        factory.setTimeout(timeout);
//        factory.setPoolConfig(jedisPoolConfig());
//        factory.setUsePool(true);
//        return factory;
//    }



    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        template.setDefaultSerializer(jackson2JsonRedisSerializer);

//        template.setConnectionFactory(jedisConnectionFactory());
//        template.setKeySerializer(keySerializer());
//        template.setHashKeySerializer(keySerializer());

        template.setValueSerializer(valueSerializer());
//        template.setHashValueSerializer(valueSerializer());
//        template.setEnableTransactionSupport(true);

        template.afterPropertiesSet();

        return template;
    }


//    // 创建redis的key序列化规则
//    private RedisSerializer<?> keySerializer() {
//        return new StringRedisSerializer();
//    }
//
//    // 值使用jackson进行序列化
    private RedisSerializer<?> valueSerializer() {
        return new GenericJackson2JsonRedisSerializer();
        // return new JdkSerializationRedisSerializer();
    }
}
